from typing import List, Dict

import pymysql


def insert(table, data):
    # 这里你知道table和data，其中data是一个字典，写插入数据库的代码
    column = data[0]
    cols = ", ".join('`{}`'.format(k) for k in column.keys())
    print(cols)  # '`name`, `age`'

    val_cols = ', '.join('%({})s'.format(k) for k in column.keys())
    print(val_cols)  # '%(name)s, %(age)s'
    sql = "insert into " + table + "(%s) values(%s)"
    res_sql = sql % (cols, val_cols)
    print(res_sql)
    return res_sql


# 数据库连接配置
DB_CONFIG = {
    'host': '10.24.53.140',
    'port': 3306,
    'user': 'jpgs',
    'password': '43HRDd7k8jvaR',
    'db': 'jpgs',
    'charset': 'utf8mb4',  # 根据需要调整字符集
}

# 数据库连接配置
PROJECT_DB_CONFIG = {
    'host': '10.24.53.140',
    'port': 3306,
    'user': 'jpgs',
    'password': '43HRDd7k8jvaR',
    'db': 'jpgs',
    'charset': 'utf8mb4',  # 根据需要调整字符集
}

VAN_DB_CONFIG = {
    'host': '10.24.53.140',
    'dbname': 'jpgs',
    'user': 'jpgs',
    'password': '43HRDd7k8jvaR',
    'port': 3306
}


def insert_data(table_name: str, insert_data_list: List[Dict]):
    if not insert_data_list:
        return
    res_sql = insert(table_name, insert_data_list)
    try:
        with pymysql.connect(**DB_CONFIG) as db:
            with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor:
                cursor.executemany(res_sql, insert_data_list)
                db.commit()
                # 可以在这里添加其他数据库操作...
    except pymysql.MySQLError as e:
        print("MySQL错误:", e)


def obtain_data(sql: str):
    print("obtain_data**********************")
    print(sql)
    try:
        with pymysql.connect(**PROJECT_DB_CONFIG) as db:
            with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor:
                cursor.execute(sql)
                return cursor.fetchall()
    except pymysql.MySQLError as e:
        print("MySQL错误:", e)


def modify_data(sql: str):
    print("modify_data**********************")
    print(sql)
    try:
        with pymysql.connect(**PROJECT_DB_CONFIG) as db:
            with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor:
                cursor.execute(sql)
                db.commit()
    except pymysql.MySQLError as e:
        print("MySQL错误:", e)
